package com.cjh.lms.controller;

import java.io.IOException;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.tools.ant.types.resources.LogOutputResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cjh.lms.pojo.TUser;
import com.cjh.lms.service.LoginService;
import com.cjh.lms.CAP.Captcha;
import com.cjh.lms.CAP.GifCaptcha;


@Controller
public class LoginController {
	
	@Resource
	private LoginService loginService;
	
	//登录
	@RequestMapping("login.do")
	public String finduser(String username,String userpwd,String captcha,HttpServletResponse response,HttpServletRequest request,Map<String, String> map)throws Exception{
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		
		HttpSession session = request.getSession();	
		String _code = (String) session.getAttribute("_code");
		if(_code.length()<1){
			return "login";
		}
		if(!captcha.equalsIgnoreCase(_code)){
			map.put("result", "验证码错误");	
			return "login";
		}
		
		TUser user = loginService.login(username,userpwd);
		if(user==null){
			map.put("result", "账号密码不匹配");
			return "login";
		}else{
			map.put("username", user.getUsername());
			HttpSession session1 = request.getSession();
			session1.setAttribute("userKey", user);
			return "bjui_index";
		}
	}	
	
	//修改密码
	@RequestMapping("changPassword")
	@ResponseBody
	public Object changPassword(String password,String newPassword,HttpServletRequest requset){
		TUser tUser = new TUser();
		tUser = (TUser)requset.getSession().getAttribute("userKey");
		String username = tUser.getUsername();
		return loginService.changPassword(username, password,newPassword);
	}
	
	//注销登录
	@RequestMapping("logout")
	@ResponseBody
	public String logout(){
		return "login";
	}
	/**
	 * 获取验证码（Gif版本）
	 * @param response
	 * @throws IOException 
	 */
	@RequestMapping(value="getGifCode",method=RequestMethod.GET)
	public void getGifCode(HttpServletResponse response,HttpServletRequest request) throws IOException{
			response.setHeader("Pragma", "No-cache");  
	        response.setHeader("Cache-Control", "no-cache");  
	        response.setDateHeader("Expires", 0);  
	        response.setContentType("image/gif");  
	        /**
	         * gif格式动画验证码
	         * 宽，高，位数。
	         */
	        Captcha captcha = new GifCaptcha(146,33,4);
	        //输出
	        captcha.out(response.getOutputStream());
	        HttpSession session = request.getSession(true);  
	        //存入Session
	        session.setAttribute("_code",captcha.text().toLowerCase()); 
	}

}
